// 函数组件
import React, { useState, useEffect, useContext } from 'react';

import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts';
// import "./js/CustomCharts.tsx"

import "./css/TransactionStatistics.less"
import { DatePicker, Space, Badge, Descriptions } from 'antd';
import { tradeData, tradeOrderData } from '../../../api/statistics';
import type { DatePickerProps, RangePickerProps } from 'antd/es/date-picker';
const { RangePicker } = DatePicker;
interface TradeData {
    endTime?: string,
    startTime?: string,
    time?: string,
}
interface DataList {
    look: string,
    place_order_person: string,
    orderNUm: string,
    order_money: string,
    pay_goods: string,
    pay_money: string,
    pay_order: string,
    pay_person: string,
    place_order_goods: string,
    refund_money: string,
    unit_price: string,
    effective_order: string,
}
function TransactionStatistics() {
    const { RangePicker } = DatePicker;
    const [dayTime, setDayTime] = useState<string>('late7') //日期选择
    const [dayTimeTwo, setDayTimeTwo] = useState<string>('late7') //日期选择
    const [dataList, setDataList] = useState<DataList>() //数据列表
    const [nowTime, setNowTime] = useState<number>(3) //数据当前显示界面
    const [nowTimeTwo, setNowTimeTwo] = useState<number>(3) //交易当前显示界面
    const [pay, setPay] = useState<string>() //成交转化率
    const [order, setOrder] = useState<string>() //下单转化率
    const [buy, setBuy] = useState<string>() //付款转化率
    const [endTime, setendTime] = useState<string>()  //第一部分最后时间
    const [startTime, setstartTime] = useState<string>()  //第一部分最初时间
    const [endTimeTwo, setendTimeTwo] = useState<string>()  //第二部分最后时间
    const [startTimeTwo, setstartTimeTwo] = useState<string>()  //第二部分最初时间
    const [payList, setPayList] = useState<number[]>([]) //数据当前显示界面
    useEffect(() => {
        showStatistics({ time: dayTime })
        
    }, [dayTime])
    useEffect(() => {
       
        showOrder({ time: dayTimeTwo })
    }, [dayTimeTwo])

    const showStatistics = (value: TradeData) => {
        // console.log(pageNum, pageSize);
        tradeData(value).then(res => {
            console.log('所有信息', res.data);
            setDataList(res.data)
            let payProbability = Number((res.data.pay_person / res.data.look) * 100).toFixed(1)
            payProbability += "%"
            setPay(payProbability)
            let orderProbability = Number((res.data.place_order_person / res.data.look) * 100).toFixed(1)
            orderProbability += "%"
            setOrder(orderProbability)
            let buyProbability = Number((res.data.pay_person / res.data.place_order_person) * 100).toFixed(1)
            buyProbability += "%"
            setBuy(buyProbability)
        }).catch(err => {
            console.log('所有信息', err);
        })
    }
    const showOrder = (value: TradeData) => {
        // console.log(pageNum, pageSize);
        tradeOrderData(value).then(res => {
            console.log('所有信息', res.data);
            setPayList(res.data)
        }).catch(err => {
            console.log('所有信息', err);
        })
    }
    const getOption = () => {
        let option = {  //指定图表的配置项和数据
            color: ['lightblue', 'rgba(0,150,0,0.5)', 'rgba(255,200,0,0.5)',
                'rgba(155,200,50,0.5)', 'rgba(44,44,0,0.5)', 'rgba(33,33,30,0.5)',
                'rgba(255,66,0,0.5)', 'rgba(155,23,31,0.5)', 'rgba(23,44,55,0.5)'],
            //配置标题组件
            title: { left: 25, top: 0, textStyle: { color: 'black', fontSize: "14px" }, text: '数据漏斗' },
            backgroundColor: '#FFFFFF',  //rgba设置透明度0.1
            tooltip: { trigger: 'item', formatter: "{a} <br/>{b} : {c}%" },  //配置提示框组件
            // toolbox: {
            //     left: 555, top: 0,
            //     feature: {
            //         dataView: { readOnly: false },
            //         restore: {}, saveAsImage: {}
            //     }
            // },  //配置工具箱组件
            legend: {
                left: 40, top: 30, data: ['浏览', '下单', '付款',
                ]
            },  //配置图例组件
            calculable: true,
            series: [  //配置数据系列
                {
                    name: '漏斗图', type: 'funnel', left: '3%',
                    sort: 'descending',  //金字塔:'ascending'; 漏斗图:'descending'
                    top: 60, bottom: 60, width: '80%',
                    min: 0, max: 100,
                    minSize: '0%',  //设置每一块的最小宽度
                    maxSize: '100%',  //设置每一块的最大，一次去除掉尖角
                    gap: 2,  //设置每一块之间的间隔
                    label: { show: true, position: 'inside' },  //设置标签显示在里面|外面
                    labelLine: {
                        length: 10,  //设置每一块的名字前面的线的长度
                        lineStyle: {
                            width: 10,  //设置每一块的名字前面的线的宽度
                            type: 'solid'//设置每一块的名字前面的线的类型
                        }
                    },
                    itemStyle: {
                        normal: {  //设置图形在正常状态下的样式 
                            label: { show: true, fontSize: 15, color: 'blue', position: 'inside', },
                            borderColor: '#fff',  //设置每一块的边框颜色
                            borderWidth: 0,  //设置每一块边框的宽度
                            shadowBlur: 50,  //设置整个外面的阴影厚度
                            shadowOffsetX: 0,  //设置每一块的y轴的阴影
                            shadowOffsetY: 50,  //设置每一块的x轴的阴影
                            shadowColor: 'rgba(0,255,0,0.4)'//设置阴影颜色
                        }
                    },
                    //设置鼠标hover时高亮样式
                    emphasis: { label: { fontFamily: "楷体", color: 'green', fontSize: 28 } },
                    data: [  //设置在漏斗图中展示的数据 
                        { value: dataList?.look, name: '浏览' }, { value: dataList?.place_order_person, name: '下单' },
                        { value: dataList?.pay_person, name: '付款' },]
                }
            ]
        }
        return option
    }
    const getOptionTwo = () => {
        let option = {
            xAxis: {
                name: '订单金额（元）',
                type: 'category',
                data: ['0-50', '50-100', '100-200', '200-500', '500-1000', '1000-2000', '2000-5000', '5000以上'],
                axisLine: {
                    symbol: ['none', 'arrow'],
                    symbolOffset: 14,
                    lineStyle: {
                        color: '#21a6e6',
                        width: 2,
                        type: 'dashed',
                    }
                },
            },
            yAxis: {
                name: '付款订单数（单)',
                type: 'value',
                min: 0, // 最小值
                max: 70,// 最大值
                interval: 10,// 等分间隔
                axisLine: {
                    show: true,
                    symbol: ['none', 'arrow'],
                    symbolOffset: 14,
                    lineStyle: {
                        color: '#21a6e6',
                        width: 2,
                        type: 'dashed',
                    }
                },
            },
            series: [
                {
                    data: payList,
                    type: 'bar',
                    label: {
                        normal: {
                            show: true,//开启显示
                            position: 'top',//柱形上方
                            textStyle: { //数值样式
                                color: 'black'
                            }
                        }
                    }
                }
            ]
        };
        return option
    }
    const setOption = () => {
        let option = {
            title: {
                x: 'center',
                textStyle: {
                    color: 'rgba(0, 0, 0, 0.9)',
                    fontWeight: 400,
                    fontSize: 14,
                },
            },
            tooltip: {
                trigger: 'item',
                //提示框浮层内容格式器，支持字符串模板和回调函数形式。
                formatter: '{a} <br/>{b} : {c} ({d}%)',
            },
            legend: {
                orient: 'horizontal',
                bottom: 5,
                data: ['新客户', '老客户'],
                itemWidth: 8,
                itemHeight: 8,
                icon: 'circle',
                borderRadius: 16,
            },
            series: [
                {
                    name: `总授予`,
                    type: 'pie',
                    width: 300,
                    height: 300,
                    top: 8,
                    left: 'center',
                    data: [
                        {
                            value: 1111,
                            name: '新客户',
                            label: {
                                show: true,
                                //自定义内容
                                formatter: String('paramAssign'),
                                /* formatter: () => {
                                    if (paramAssign && paramAssign !== 0) {
                                        return String(paramAssign);
                                    } else {
                                        return '';
                                    }
                                }, */
                                color: '#fff',
                            },
                            itemStyle: { color: '#41D1A6' },
                        },
                        {
                            value: 1111,
                            name: '老客户',
                            label: {
                                show: true,
                                //自定义内容
                                formatter: String('1111'),
                                color: '#fff',
                            },
                            itemStyle: { color: '#607CE9' },
                        },
                    ],
                    clockwise: false, //是否顺时针
                    label: {
                        //去除饼图的指示折线label
                        normal: {
                            show: false,
                            position: 'inside',
                            formatter: '{b}:{d}%',
                        },
                    },
                },
            ],
        };
        return option
    }
    //上部改变时间
    const changeTime = (e: number) => {
        setNowTime(e)
        if (e == 1) {
            setDayTime('yesterday')
        }
        if (e == 2) {
            setDayTime('late7')
        }
        if (e == 3) {
            setDayTime('late30')
        }
        showStatistics({ time: dayTime })
    }
    //中部改变时间
    const changeTimeTwo = (e: number) => {
        setNowTimeTwo(e)
        if (e == 1) {
            setDayTimeTwo('yesterday')
        }
        if (e == 2) {
            setDayTimeTwo('late7')
        }
        if (e == 3) {
            setDayTimeTwo('late30')
        }
        showOrder({ time: dayTimeTwo })

    }
    const onChange = (
        value: DatePickerProps['value'] | RangePickerProps['value'],
        dateString: [string, string] | string,
    ) => {
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
        setstartTime(dateString[0])
        setendTime(dateString[1])
        showStatistics({ endTime: endTime, startTime: startTime })
    };
    const onChangeTwo = (
        value: DatePickerProps['value'] | RangePickerProps['value'],
        dateString: [string, string] | string,
    ) => {
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
        setstartTimeTwo(dateString[0])
        setendTimeTwo(dateString[1])
        showOrder({ endTime: endTime, startTime: startTime })
    };

    return (
        <div className='TransactionStatistics'>
            {/* 头部 */}
            <div className='page-top'>
                {/* 左边标题 */}
                <div className='page-title'>
                    <p>交易统计</p>
                </div>
            </div>
            {/* 内容区 */}
            <div className='page-context'>
                {/* 数据表部分 */}
                <div className='data-list'>
                    {/* 上部文字 */}
                    <div className='list-text'>
                        <p>数据列表</p>
                        <div>
                            <button className={nowTime == 1 ? 'blue' : ''} onClick={() => changeTime(1)}>昨天</button>
                            <button className={nowTime == 2 ? 'blue' : ''} onClick={() => changeTime(2)}>最近7天</button>
                            <button className={nowTime == 3 ? 'blue' : ''} onClick={() => changeTime(3)}>最近30天</button>
                            <Space direction="vertical" size={12}>
                                <RangePicker renderExtraFooter={() => 'extra footer'} showTime onChange={onChange} />
                            </Space>
                        </div>
                    </div>
                    {/* 表格数据 */}
                    <div className="table-context">
                        <Descriptions title="数据概览" bordered column={6} layout="vertical">
                            <Descriptions.Item label="浏览人数">{dataList?.look}</Descriptions.Item>
                            <Descriptions.Item label="下单人数">{dataList?.place_order_person}</Descriptions.Item>
                            <Descriptions.Item label="订单数">{dataList?.orderNUm}</Descriptions.Item>
                            <Descriptions.Item label="下单件数">{dataList?.place_order_goods}</Descriptions.Item>
                            <Descriptions.Item label="有效订单数">{dataList?.effective_order}</Descriptions.Item>
                            <Descriptions.Item label="下单金额">{dataList?.order_money}</Descriptions.Item>
                            <Descriptions.Item label="退款金额">{dataList?.refund_money}</Descriptions.Item>
                            <Descriptions.Item label="付款人数">{dataList?.pay_person}</Descriptions.Item>
                            <Descriptions.Item label="付款订单数">{dataList?.place_order_goods}</Descriptions.Item>
                            <Descriptions.Item label="付款件数">{dataList?.pay_goods}</Descriptions.Item>
                            <Descriptions.Item label="付款金额">{dataList?.pay_money}</Descriptions.Item>
                            <Descriptions.Item label="客单价">{dataList?.unit_price}</Descriptions.Item>
                        </Descriptions>
                    </div>
                    <div className='Echarts'>
                        <ReactECharts option={getOption()} style={{ height: '400px' }} />
                        <div className='Echarts-text'>
                            <p className='text-one'>浏览——&gt;付款：成交转化率 {pay}</p>
                            <p className='text-two'>浏览——&gt;下单：下单转化率 {order}</p>
                            <p>下单——&gt;付款：付款转化率 {buy}</p>
                        </div>
                    </div>
                </div>
                <div className='data-listone'>
                    {/* 上部文字 */}
                    <div className='list-text'>
                        <p>交易数据</p>
                        <div>
                            <button className={nowTimeTwo == 1 ? 'blue' : ''} onClick={() => changeTimeTwo(1)}>昨天</button>
                            <button className={nowTimeTwo == 2 ? 'blue' : ''} onClick={() => changeTimeTwo(2)}>最近7天</button>
                            <button className={nowTimeTwo == 3 ? 'blue' : ''} onClick={() => changeTimeTwo(3)}>最近30天</button>
                            <Space direction="vertical" size={12}>
                                <RangePicker renderExtraFooter={() => 'extra footer'} showTime onChange={onChangeTwo}  />
                            </Space>
                        </div>
                    </div>
                    {/* 表格数据 */}
                    <div className='Echarts'>
                        <ReactECharts option={getOptionTwo()} style={{ height: '400px' }} />
                    </div>
                </div>
                <div className='data-listTwo'>
                    {/* 上部文字 */}
                    <div className='list-text'>
                        <p>
                            新老客户交易构成</p>
                        <div>
                            <button>本月</button>
                            <button>上月</button>
                            <Space direction="vertical" size={12}>
                                <DatePicker renderExtraFooter={() => 'extra footer'} />
                            </Space>
                        </div>
                    </div>
                    {/* 表格数据 */}
                    <div className='Echarts'>
                        <ReactECharts option={setOption()} style={{ height: '350px' }} />
                    </div>
                    <div className='table-last'>
                        <ul className='table-ul'>
                            <ul>
                                <li>客户类型</li>
                                <li>新客户</li>
                                <li>老客户</li>
                            </ul>
                            <ul>
                                <li>付款金额</li>
                                <li>新客户</li>
                                <li>老客户</li>
                            </ul>
                            <ul>
                                <li>较前一月</li>
                                <li>新客户</li>
                                <li>老客户</li>
                            </ul>
                            <ul>
                                <li>付款人数</li>
                                <li>新客户</li>
                                <li>老客户</li>
                            </ul>
                            <ul>
                                <li>较前一月</li>
                                <li>新客户</li>
                                <li>老客户</li>
                            </ul>
                        </ul>
                    </div>
                </div>
                <div className='footer'></div>
            </div>
        </div>
    )
}

export default TransactionStatistics